<?php

class categoryPageActions extends myFrontendAction
{
	
	public function executeTest(){
		$this->getRoute()->getObject();
	}

	public function preExecute(){
		parent::preExecute();
		//$this->setLayout('layout_widgets_off');

		$this->category = $this->getRoute()->getCategoryObject();
	}

	static private $showByAr = array(50 => 50);
	static private $sortByAr = array('A-Z' => 'name', 'Price' => 'price');
									
	
	public function executeIndex( sfWebRequest $request )
  {
    // List of the products
		$this->pager = new sfDoctrinePager('Product');
    $this->pager->setQuery( $this->getCategoryProductsQuery() );
    $this->pager->setPage($request->getParameter('page', 1));
  	$this->pager->init();
    
    // Include product pictures as well
    $this->pictures = Doctrine::getTable('Product')->getRelatedPictures($this->pager);
    
    // Category
		$this->category = $this->getRoute()->getCategoryObject();
	}


	public function executeSortBy(sfWebRequest $request){
		if($request->hasParameter('sort') && in_array($request->getParameter('sort'), self::$sortByAr)){
			$this->setSort($request->getParameter('sort'));
		}

		$this->redirect(LinkGen::getInstance(LinkGen::PRODUCT_GROUP)->link($this->category['id']));
	}

	public function executeShowBy(sfWebRequest $request){

		if($request->hasParameter('show') && in_array($request->getParameter('show'), self::$showByAr)){
			$this->setShowby($request->getParameter('show'));
		}

		$this->redirect(LinkGen::getInstance(LinkGen::PRODUCT_GROUP)->link($this->category['id']));
	}

	protected function getShowBy(){
		if($this->getUser()->getAttribute('show')){
			return $this->getUser()->getAttribute('show');
		}else
			return 10;
	}

	protected function getShowIn(){
		if($this->getUser()->getAttribute('showin')){
			return $this->getUser()->getAttribute('showin');
		}else
			return 'list';
	}

	protected function getSort(){
		if( $this->getUser()->getAttribute('sort') ){
			return $this->getUser()->getAttribute('sort');
		}else{
			return current(self::$sortByAr);
		}
	}

	protected function setSort($sort){
		$this->getUser()->setAttribute('sort', $sort);
	}

	protected function setShowby($show){
		$this->getUser()->setAttribute('show', $show);
	}

	private function getCategoryProductsQuery(){

		$q = Doctrine::getTable('Product')
					->getAssociatedToCategoryProductsQuery( $this->getRoute()->getCategoryObject()->getId() );

		return $this->setCategoryQueryConstraints($q);
	}

	protected function setCategoryQueryConstraints( Doctrine_Query $q ){
		$q->innerJoin($q->getRootAlias().'.Translation t');

		Doctrine::getTable('Product')->addProductPicturesJoin( $q );


		switch($this->getSort()){
			case 'name':
				$q->orderBy('t.name asc');
				break;
			case 'price':
				$q->orderBy($q->getRootAlias() . '.price asc');
				break;
		}


		return $q;
	}

	  
}